/**
 *   FuzzyEngine - an Simple flex framework 
 *   Copyright (C) 2010 Constantin Aldea
 *
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package fuzzy.penelope.core.dataservices.filters {
	import fuzzy.penelope.model.ErrorManager;
	import fuzzy.penelope.model.errors.interfaces.IServiceError;
	import fuzzy.penelope.model.vo.framework.access.Persona;
	import fuzzy.penelope.model.vo.framework.exceptions.ServiceException;
	import fuzzy.penelope.model.vo.framework.exceptions.SystemException;

	import project.enums.ErrorsEnumKey;

	import com.googlecode.flexxb.FlexXBEngine;

	import mx.managers.CursorManager;
	import mx.rpc.http.AbstractOperation;
	import mx.rpc.http.SerializationFilter;

	public class FuzzySerializerFilter extends SerializationFilter {
		private var serializer : FlexXBEngine;

		
		public function FuzzySerializerFilter() {
			super();
			serializer = FlexXBEngine.instance;
			serializer.processTypes(ServiceException, SystemException, Persona); 		
		}

		
		
		override public function deserializeResult(operation : AbstractOperation, result : Object) : Object {	
			var xmlData : XML = null;
			var _res : Object = null;
			try {
				xmlData = new XML(result);
				_res = serializer.deserialize(new XML(result));		
			}catch(e : Error) {
				var exeption : SystemException = new SystemException();
				exeption.detailMessage = ErrorsEnumKey.ERRORE_DESERIALIZER + e.message;
				_res = exeption;  
			} 
			
			
			CursorManager.removeAllCursors();
			if(_res is ServiceException || _res is SystemException) {
				ErrorManager.getInstance().serviceError(_res as IServiceError);
				return _res;
			}
			
			if(_res != null) return _res;
			else return result;
		}

		override public function serializeBody(operation : AbstractOperation, obj : Object) : Object {
			var _res : XML = null;
			if(obj is XML) return obj; else {
				try {
					_res = serializer.serialize(obj);	
				}catch(e : Error) {
					throw new Error(ErrorsEnumKey.ERRORE_SERIALIZER + e.message);  	
				}	
			}   
			return _res;
		}
	}
}